/* 
 * Copyright (C) 2001-2003 Jacek Sieka, j_s@telia.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#if !defined(AFX_CLIENTMANAGER_H__8EF173E1_F7DC_40B5_B2F3_F92297701034__INCLUDED_)
#define AFX_CLIENTMANAGER_H__8EF173E1_F7DC_40B5_B2F3_F92297701034__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "TimerManager.h"

#include "Client.h"
#include "Singleton.h"

#include "ClientManagerListener.h"
#include "SearchManager.h"
#include "SettingsManager.h"

class ClientManager : public Speaker<ClientManagerListener>, 
	private ClientListener, public Singleton<ClientManager>, 
	private TimerManagerListener, private SearchManagerListener
{
public:
	Client* getClient(/*const string& aHubURL*/);

	void putClient(Client* aClient);

	int getUserCount() {
		Lock l(cs);

		int c = 0;
		for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
			c+=(*i)->getUserCount();
		}
		return c;
	}

	int64_t getAvailable() {
		Lock l(cs);
		
		int64_t c = 0;
		for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
			c+=(*i)->getAvailable();
		}
		return c;
	}

	bool isConnected(const string& aAddress, short port) {
		Lock l(cs);

		for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
			if(((*i)->getAddress() == aAddress || (*i)->getIp() == aAddress) && (*i)->getPort() == port) {
				return true;
			}
		}
		return false;
	}
	
	void search(int aSizeMode, int64_t aSize, int aFileType, const string& aString) {
		Lock l(cs);

		for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
			if((*i)->isConnected()) {
				(*i)->search(aSizeMode, aSize, aFileType, aString);
			}
		}
	}

	void search(StringList& who, int aSizeMode, int64_t aSize, int aFileType, const string& aString) {
		Lock l(cs);

		for(StringIter it = who.begin(); it != who.end(); ++it) {
			string& client = *it;
			for(Client::Iter j = clients.begin(); j != clients.end(); ++j) {
				Client* c = *j;
				if(c->isConnected() && c->getIpPort() == client) {
					c->search(aSizeMode, aSize, aFileType, aString);

				}
			}
		}
	}

	void infoUpdated();

	User::Ptr getUser(const string& aNick, const string& aHint = Util::emptyString);
	User::Ptr getUser(const string& aNick, Client* aClient, bool putOnline = true);
	
	bool isOnline(const string& aNick) {
		Lock l(cs);
		UserPair i = users.equal_range(aNick);
		for(UserIter j = i.first; j != i.second; ++j) {
			if(j->second->isOnline())
				return true;
		}
		return false;
	}

	/**
	 * A user went offline. Must be called whenever a user quits a hub.
	 * @param quitHub The user went offline because (s)he disconnected from the hub.
	 */
	void putUserOffline(User::Ptr& aUser, bool quitHub = false) {
		{
			Lock l(cs);

			aUser->setIp(Util::emptyString);
			aUser->unsetFlag(User::PASSIVE);
			aUser->unsetFlag(User::OP);
			aUser->unsetFlag(User::DCPLUSPLUS);
			// CDM EXTENSION BEGINS
			aUser->unCacheClientInfo(true, true);
			// CDM EXTENSION ENDS
			if(quitHub)
				aUser->setFlag(User::QUIT_HUB);
			aUser->setClient(NULL);
		}
		fire(ClientManagerListener::USER_UPDATED, aUser);
	}
	
	void lock() throw() { cs.enter(); }
	void unlock() throw() { cs.leave(); }

	Client::List& getClients() { return clients; }

 	void removeClientListener(ClientListener* listener) {
 		Lock l(cs);
 		Client::Iter endIt = clients.end();
 		for(Client::Iter it = clients.begin(); it != endIt; ++it) {
 			Client* client = *it;
 			client->removeListener(listener);
 		}
 	}

	const string& getIPNick(const string& IP) const {
		NickMap::const_iterator it;
		if ((it = ipList.find(IP)) != ipList.end() && !it->second.empty())
			return it->second;
		else
			return IP;
	}

	// CDM EXTENSION BEGINS
	void setIPNick(const string& IP, const string& Nick, bool addToList = false) {
		if (addToList) {
			ipList[IP] = Nick;
			getUser(Nick)->setUserIp(IP);
		} else {
			getUser(Nick)->setIp(IP);
		}
		getUser(Nick)->setCountry();
	}
	void setHostNick(const string& ip, const string& host, const string& Nick) {
		getUser(Nick)->setIpAndHost(ip, host);
		getUser(Nick)->setCountry();
	}
	bool isHubCountFaking(User::Ptr& aUser, const int statedHubs);
	void multiHubKick(User::Ptr& aUser, const string& aReason);
	//Sulan start svn 168
	User::List findUser(User::Ptr& aUser, bool forFilelist);
	bool CheckSharingHub(User::Ptr& aUser);
	void multiHubRaw(int aRaw, User::Ptr& aUser);
	//End
	//Sulan
	void reloadFavHubs();
	// CDM EXTENSION ENDS
	// pothead extension starts #3 #8 and (r2 code) svn62 svn162 svn179
	void multiHubBanIp(const string& aIp, const string& aReason);
	int getTotalUsers();
	int64_t getTotalShare();
	// pothead extension ends
private:
	typedef HASH_MULTIMAP<string, User::Ptr> UserMap;
	typedef UserMap::iterator UserIter;
	typedef pair<UserIter, UserIter> UserPair;
	typedef set<User::Ptr> UserSet;
	typedef map<string, string> NickMap;

	Client::List clients;
	CriticalSection cs;
	
	StringList features;
	UserMap users;
	Socket s;

 	NickMap ipList;

	friend class Singleton<ClientManager>;

	ClientManager() { 
		TimerManager::getInstance()->addListener(this); 
		SearchManager::getInstance()->addListener(this);

		features.push_back("UserCommand");
		features.push_back("NoGetINFO");
		features.push_back("NoHello");
		features.push_back("UserIP2");
		features.push_back("ZLine");
	};

	virtual ~ClientManager() { TimerManager::getInstance()->removeListener(this); };
	// ClientListener
	virtual void on(Connected, Client* c) throw() { fire(ClientManagerListener::CLIENT_CONNECTED, c); }
	virtual void on(UserUpdated, Client*, const User::Ptr& user) throw() { fire(ClientManagerListener::USER_UPDATED, user); }
	virtual void on(UsersUpdated, Client* c, const User::List&) throw() { fire(ClientManagerListener::CLIENT_UPDATED, c); }
	virtual void on(Failed, Client*, const string&) throw();
	virtual void on(HubName, Client*) throw();
	virtual void on(UserCommand, Client*, int, int, const string&, const string&) throw();
	virtual void on(ConnectToMe, Client*, const string&, const string&) throw();
	virtual void on(CLock, Client*, const string&, const string&) throw();
	virtual void on(RevConnectToMe, Client*, const User::Ptr&) throw();
	virtual void on(Search, Client*, const string&, int, const string&, int, const string&) throw();
	virtual void on(RawMessage, Client*, const string&) throw();

	void onClientHello(Client* aClient, const User::Ptr& aUser) throw();
	void onClientSearch(Client* aClient, const string& aSeeker, int aSearchType, const string& aSize, 
		int aFileType, const string& aString) throw();
	void onClientLock(Client* aClient, const string& aLock) throw();

	// TimerManagerListener
	virtual void on(TimerManagerListener::Minute, u_int32_t aTick) throw();
	void onTimerMinute(u_int32_t aTick);

	// SearchManagerListener
	void on(SearchManagerListener::SR, SearchResult*) throw();
	void on(SearchManagerListener::SR, const string &aLine) throw();
public:
	string findNickIp(const string& aHint);
};

#endif // !defined(AFX_CLIENTMANAGER_H__8EF173E1_F7DC_40B5_B2F3_F92297701034__INCLUDED_)

/**
 * @file
 * $Id: ClientManager.h 255 2005-07-16 13:06:57Z Flow84 $
 */